package com.pig4cloud.pig.module.service.product.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.pig.common.core.exception.TransactionalException;
import com.pig4cloud.pig.common.core.exception.YshopException;
import com.pig4cloud.pig.module.api.entity.dto.AttrValueDto;
import com.pig4cloud.pig.module.api.entity.dto.FromatDetailDto;
import com.pig4cloud.pig.module.api.entity.dto.ProductFormatDto;
import com.pig4cloud.pig.module.api.entity.product.ProductAttr;
import com.pig4cloud.pig.module.api.entity.product.ProductAttrValue;
import com.pig4cloud.pig.module.mapper.product.ProductAttrMapper;
import com.pig4cloud.pig.module.mapper.product.ProductAttrValueMapper;
import com.pig4cloud.pig.module.service.product.IProductAttrResultService;
import com.pig4cloud.pig.module.service.product.IProductAttrService;
import com.pig4cloud.pig.module.service.product.IProductAttrValueService;
import io.undertow.util.BadRequestException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 商品属性Service业务层处理
 *
 * @author ruoyi
 * @date 2021-08-11
 */
@Service
public class ProductAttrServiceImpl extends ServiceImpl<ProductAttrMapper, ProductAttr> implements IProductAttrService {

	@Resource
	private ProductAttrMapper productAttrMapper;
	@Resource
	private ProductAttrValueMapper productAttrValueMapper;
	@Resource
	private IProductAttrValueService productAttrValueService;
	@Resource
	private IProductAttrResultService productAttrResultService;

//	@Value("${ruoyi.imgUrl}")
//	private String imgUrl;

	@Value("${ruoyi.imgUrlOss}")
	private String imgUrlOss;

	/**
	 * 新增商品属性
	 * @param items attr
	 * @param attrs value
	 * @param productId 商品id
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void insertProductAttr(List<FromatDetailDto> items, List<ProductFormatDto> attrs, Long productId) {
		try{
//			List<ProductAttr> attrGroup = new ArrayList<>();

			productAttrMapper.delete(Wrappers.<ProductAttr>lambdaQuery()
				.eq(ProductAttr::getProductId,productId));

			for (FromatDetailDto fromatDetailDto : items) {
				QueryWrapper<ProductAttr> qw = new QueryWrapper<>();
				qw.eq("product_id",productId);
				qw.eq("attr_name",fromatDetailDto.getValue());
				ProductAttr productAttr = productAttrMapper.selectOne(qw);
				if(productAttr == null){
					productAttr = new ProductAttr();
					productAttr.setProductId(productId);
					productAttr.setAttrName(fromatDetailDto.getValue());
					productAttr.setAttrValues(StrUtil.join(",",fromatDetailDto.getDetail()));
					productAttrMapper.insert(productAttr);
				}else{
					productAttr.setAttrValues(StrUtil.join(",",fromatDetailDto.getDetail()));
					productAttrMapper.updateById(productAttr);
				}
			}


			QueryWrapper<ProductAttrValue> qw = new QueryWrapper<>();
			qw.eq("product_id",productId);
			qw.eq("is_del",0);
			//当前拥有的规格
			List<ProductAttrValue> attrValues = productAttrValueMapper.selectList(qw);
			//当前选中的
			List<ProductAttrValue> valueGroup = new ArrayList<>();
			//新增的规格
			List<ProductAttrValue> newValueGroup = new ArrayList<>();
			for (ProductFormatDto productFormatDto : attrs) {
				if(productFormatDto.getPinkStock() > productFormatDto.getStock()){
					throw new BadRequestException("活动商品库存不能大于原有商品库存");
				}
				List<String> stringList = new ArrayList<>(productFormatDto.getDetail().values());
				Collections.sort(stringList);

				String sku = StrUtil.join(",",stringList);

				//获取当前前端传过来的规格信息
				ProductAttrValue productAttrValue = getValueByDto(productId,sku,productFormatDto);

				QueryWrapper<ProductAttrValue> qw1 = new QueryWrapper<>();
				qw1.eq("product_id",productId);
				qw1.eq("sku",sku);
				qw1.last("limit 1");
				//当前数据库里存在的sku 规格信息
				ProductAttrValue attrValue = productAttrValueMapper.selectOne(qw1);
				//之前没有规格 全部新加
				if(attrValue == null) {
					//新添加的
					productAttrValue.setIsDel(0);
					newValueGroup.add(productAttrValue);
				}else{//存在之前的规格
					productAttrValue.setPrice(new BigDecimal(productFormatDto.getPrice()));
					productAttrValue.setCost(new BigDecimal(productFormatDto.getCost()));
					productAttrValue.setOtPrice(new BigDecimal(productFormatDto.getOtPrice()));
					productAttrValue.setWeight(new BigDecimal(productFormatDto.getWeight()));
					productAttrValue.setVolume(new BigDecimal(productFormatDto.getVolume()));
					productAttrValue.setPinkPrice(new BigDecimal(productFormatDto.getPinkPrice()));

					if(productAttrValue.getIsDel() ==null){
						productAttrValue.setIsDel(0);
					}
					if(attrValue.getIsDel() == 1){
						productAttrValue.setId(attrValue.getId());
						productAttrValue.setIsDel(0);
					}
					productAttrValueMapper.updateById(productAttrValue);
				}
				//当前选择的规格
				valueGroup.add(productAttrValue);
			}
			//清理属性
//		this.clearProductAttr(productId);

			//批量添加规格属性
			if(newValueGroup.size() > 0){
				productAttrValueService.saveBatch(newValueGroup);
			}

			//选出删除不要的规格
			for (ProductAttrValue value : attrValues){
				int isHas = 0;
				for(ProductAttrValue nowValue : valueGroup){
					if(value.getSku().equals(nowValue.getSku())){
						isHas = 1;
						break;
					}
				}
				if(isHas == 0){
					value.setIsDel(1);
					productAttrValueMapper.updateById(value);
				}
			}

			Map<String,Object> map = new LinkedHashMap<>();
			map.put("attr",items);
			map.put("value",attrs);
			productAttrResultService.insertProductAttrResult(map,productId);
		}catch (Exception e){
			e.printStackTrace();
			throw new TransactionalException("insertProductAttr error");
		}
	}

	private ProductAttrValue getValueByDto(Long productId, String sku,ProductFormatDto productFormatDto){

		ProductAttrValue productAttrValue = ProductAttrValue.builder()
			.id(productFormatDto.getId())
			.productId(productId).sku(sku)
			.price(BigDecimal.valueOf(productFormatDto.getPrice()))
			.cost(BigDecimal.valueOf(productFormatDto.getCost()))
			.otPrice(BigDecimal.valueOf(productFormatDto.getOtPrice()))
			.uniqueValue(IdUtil.simpleUUID())
//				.image(productFormatDto.getImage())
//			.barCode(productFormatDto.getBarCode())
//			.weight(BigDecimal.valueOf(productFormatDto.getWeight()))
//			.volume(BigDecimal.valueOf(productFormatDto.getVolume()))
//			.brokerage(BigDecimal.valueOf(productFormatDto.getBrokerage()))
//			.brokerageTwo(BigDecimal.valueOf(productFormatDto.getBrokerageTwo()))
			.stock(productFormatDto.getStock())
//			.pinkPrice(BigDecimal.valueOf(productFormatDto.getPinkPrice()==null?0:productFormatDto.getPinkPrice()))
//			.pinkStock(productFormatDto.getPinkStock() == null ?  0 : productFormatDto.getPinkStock())
				.build();

		return productAttrValue;
	}


	/**
	 * 获取商品sku属性
	 * @param productId 商品id
	 * @return map
	 */
	@Override
	public Map<String, Object> getProductAttrDetail(long productId) {
		List<ProductAttr> storeProductAttrs = productAttrMapper.selectList(Wrappers.<ProductAttr>lambdaQuery()
				.eq(ProductAttr::getProductId,productId).orderByAsc(ProductAttr::getAttrValues));

		List<ProductAttrValue> productAttrValues = productAttrValueService.list(
				Wrappers.<ProductAttrValue>lambdaQuery().eq(ProductAttrValue::getProductId,productId)
					.eq(ProductAttrValue::getIsDel,0));
		if(CollUtil.isNotEmpty(productAttrValues)){
			productAttrValues.forEach(value->{
				if(StrUtil.isNotEmpty(value.getImage())){
					if(value.getImage().indexOf("http") < 0){
						value.setImagePath(imgUrlOss + value.getImage());
					}else{
						value.setImagePath(value.getImage());
					}
				}else{
					value.setImagePath("");
				}
			});
		}


		Map<String, ProductAttrValue> map = productAttrValues.stream().collect(Collectors.toMap(ProductAttrValue::getSku, p -> p));

		List<ProductAttr> productAttrList = new ArrayList<>();

		for (ProductAttr attr : storeProductAttrs) {
			List<String> stringList = Arrays.asList(attr.getAttrValues().split(","));
			List<AttrValueDto> attrValueDTOS = new ArrayList<>();
			for (String str : stringList) {
				AttrValueDto attrValueDTO = new AttrValueDto();
				attrValueDTO.setAttr(str);
				attrValueDTOS.add(attrValueDTO);
			}
			attr.setAttrValue(attrValueDTOS);
			attr.setAttrValueArr(stringList);
			productAttrList.add(attr);
		}

		Map<String, Object> returnMap = new LinkedHashMap<>(2);
		returnMap.put("productAttr",productAttrList);
		returnMap.put("productValue",map);
		return returnMap;
	}

	/**
	 * 删除ProductAttrValue表的属性
	 * @param productId 商品id
	 */
	private void clearProductAttr(Long productId) {
		if(ObjectUtil.isNull(productId)) {
			throw new YshopException("产品不存在");
		}

		productAttrMapper.delete(Wrappers.<ProductAttr>lambdaQuery()
			.eq(ProductAttr::getProductId,productId));
		productAttrValueMapper.delete(Wrappers.<ProductAttrValue>lambdaQuery()
			.eq(ProductAttrValue::getProductId,productId));

	}
}
